package com.yujie.controller;

import com.yujie.domain.query.UserQuery;
import com.yujie.domain.vo.UserVO;
import com.yujie.util.R;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
public class LoginController {

    @PostMapping("/login")
    public R login(@RequestBody UserQuery user, HttpSession session){
        R r = checkVerifyCode(user.getVerifyCode(), session);
        if(!r.getCode().equals("200")){
            return r;
        }

        UserVO u = new UserVO();
        if(user.getUserName().equals("admin") && user.getPassword().equals("123")){
            u.setUserName("admin");
            u.setToken(UUID.randomUUID().toString());
            //销毁当前的验证码
            session.removeAttribute("login-verifyCode");
            return R.ok().setData(u);
        }else{
            r.setCode("500");
            r.setMessage("用户名或密码错误");
            return r;
        }
    }

    private R checkVerifyCode( String code, HttpSession session){
        R r = R.ok();
        String cv = (String) session.getAttribute("login-verifyCode");
        if(cv==null){
            r.setCode("500");
            r.setMessage("验证码已过期");
            return r;
        }else if(code==null|| !cv.equalsIgnoreCase(code)){
            r.setCode("500");
            r.setMessage("验证码错误");
            return r;
        }else{
            return r;
        }
    }


}
